package com.myproject.myblogserver.service.impl;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.myproject.myblogserver.contant.CommonConstants;
import com.myproject.myblogserver.entity.User;
import com.myproject.myblogserver.entity.UserFollow;
import com.myproject.myblogserver.service.IMyUserInfoService;
import com.myproject.myblogserver.service.IUserFollowService;

@Service
public class MyUserInfoServiceImpl implements IMyUserInfoService {

    private IUserFollowService userFollowService;

    @Override
    public Map<Long, Long> getFollowerCountMap(Page<User> followerPage) {
        // 批量获取所有用户的粉丝数
        List<Long> userIds = followerPage.getRecords().stream()
                .map(User::getId)
                .collect(Collectors.toList());

        List<Map<String, Object>> counts = userFollowService.listMaps(
                new QueryWrapper<UserFollow>()
                        .select("following_id, COUNT(*) as count")
                        .eq("is_deleted", CommonConstants.DELETED_STATUS_NO)
                        .in("following_id", userIds)
                        .groupBy("following_id"));

        Map<Long, Long> followerCountMap = counts.stream()
                .collect(Collectors.toMap(
                        map -> (Long) map.get("following_id"),
                        map -> (Long) map.get("count")));

        return followerCountMap;
    }
}
